package cn.tedu.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class MyFilter1 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 处理请求参数，先要在过滤器中拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 处理响应参数，先要在过滤器中拿到响应对象
        ServerHttpResponse response = exchange.getResponse();

        // 对request做参数的获取
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        // localhost:19999/csmall-for-jsd-stock/aaa?name="zhangsan"
        List<String> paramList = queryParams.get("name");
        if (paramList == null || paramList.size() == 0) {
            log.error("当前请求没有携带name参数");
            // 如果当前参数没有name，拦截这个请求，返回自定义的响应数据
            // 定义当前响应写出数据的格式 添加一个响应头
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            // 封装一个写好响应数据的Mono对象作为返回值
//            return response.writeWith(Mono.fromSupplier(() -> {
//                // 将数据流写进response
//                return response.bufferFactory().wrap("你好，没有携带name".getBytes(StandardCharsets.UTF_8));
//            }));
            return chain.filter(exchange);
        }else {
            log.info("当前请求携带了name参数：{}", paramList.get(0));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
